package com.heimachefu.config;

import com.heimachefu.module.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

/**
 * @author liuxingdong@heimachefu.com
 * @date 2019/7/19 11:31
 */

@Configuration
@EnableWebSecurity
public class SecurityConfiguration  extends WebSecurityConfigurerAdapter {
    private final VersionSystemSuccessHandler versionSystemSuccessHandler;

    private final SystemAuthenticationProvider systemAuthenticationProvider;

    @Autowired
    public SecurityConfiguration(VersionSystemSuccessHandler versionSystemSuccessHandler,
                                 SystemAuthenticationProvider systemAuthenticationProvider) {
        this.versionSystemSuccessHandler = versionSystemSuccessHandler;
        this.systemAuthenticationProvider = systemAuthenticationProvider;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(systemAuthenticationProvider);
    }

    /**
     * 授权静态资源目录
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/assets/**");
    }

    /**
     * 授权rest接口资源信息
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/assets/**","/js/**","/user/loginPage","/user/login").permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()                    //  定义当需要用户登录时候，转到的登录页面。
                .loginPage("/user/loginPage")
                .loginProcessingUrl("/user/login")
                .successHandler(versionSystemSuccessHandler)
//                .successForwardUrl("/home/main")
                .and()
                .rememberMe()
                .and().
                //单用户登录，如果有一个登录了，同一个用户在其他地方不能登录
                sessionManagement()
                .invalidSessionUrl("/user/loginPage")
                .maximumSessions(1)
                .maxSessionsPreventsLogin(true);
                http.csrf().disable();

    }
}
